package com.atguigu.tingshu.user.config;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;

/**
 * 微信小程序登录需要用到的自动配置类
 */
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)  //好处:WxMaProperties在容器中
public class WxMinAppAutoConfiguration {


    @Autowired
    private WxMaProperties wxMaProperties;

    /**
     * 定义WxMaServiceBean对象
     * @return
     */
    @Bean
    public WxMaService wxMaService(){
        //1.得到一个WxMaService的实现类
        WxMaServiceImpl wxMaService = new WxMaServiceImpl();
        //2.得到一个wxMaDefaultConfig对象
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(wxMaProperties.getAppId());
        wxMaDefaultConfig.setSecret(wxMaProperties.getAppSecret());
        //3.给wxMaService赋值,主要位appid,appSecret
        wxMaService.setWxMaConfig(wxMaDefaultConfig);

        return wxMaService;
    }
    /**
     * 定义一个Bean对象(签名算法RSA,非对称加密)
     * 非对称加密,2把钥匙
     */
    @Bean
    public Signer rsaSigner(){

        //jdk自带的一个生成非对称加密的工具类得到一个jks证书
        //1.读取这个文件
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");
        //2.获取要是的工厂
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource,"tingshu".toCharArray());
        //3.从工厂中提取私钥对
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu","tingshu".toCharArray());
        //4.从密钥队中获取私钥
        RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();

        //得到一个非对称加密的签名算法对象
        RsaSigner rsaSigner = new RsaSigner(aPrivate);
        return rsaSigner;
    }
}
